<template>
  <div class="role-management">
    <!-- 页面标题和操作按钮 -->
    <div class="page-header">
      <h2>角色管理</h2>
      <div class="header-actions">
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          新增角色
        </el-button>
        <el-button @click="handleBatchDelete" :disabled="!selectedRoles.length">
          <el-icon><Delete /></el-icon>
          批量删除
        </el-button>
        <el-button @click="handleExport">
          <el-icon><Download /></el-icon>
          导出
        </el-button>
      </div>
    </div>

    <!-- 搜索筛选区域 -->
    <div class="search-section">
      <el-form :model="searchForm" inline>
        <el-form-item label="角色名称">
          <el-input v-model="searchForm.name" placeholder="请输入角色名称" clearable />
        </el-form-item>
        <el-form-item label="角色编码">
          <el-input v-model="searchForm.code" placeholder="请输入角色编码" clearable />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="启用" value="1" />
            <el-option label="禁用" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 数据表格 -->
    <div class="table-section">
      <el-table
        :data="tableData"
        v-loading="loading"
        @selection-change="handleSelectionChange"
        stripe
        border
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="角色名称" width="150" />
        <el-table-column prop="code" label="角色编码" width="150" />
        <el-table-column prop="description" label="角色描述" min-width="200" />
        <el-table-column prop="userCount" label="用户数量" width="100">
          <template #default="{ row }">
            <el-tag type="info">{{ row.userCount }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="160" />
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button type="warning" size="small" @click="handlePermission(row)">
              权限配置
            </el-button>
            <el-button
              :type="row.status === 1 ? 'danger' : 'success'"
              size="small"
              @click="handleToggleStatus(row)"
            >
              {{ row.status === 1 ? '禁用' : '启用' }}
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 新增/编辑角色对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="角色编码" prop="code">
          <el-input v-model="formData.code" placeholder="请输入角色编码" />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            :rows="3"
            placeholder="请输入角色描述"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="formData.sort" :min="0" :max="999" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="formData.remark"
            type="textarea"
            :rows="2"
            placeholder="请输入备注"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 权限配置对话框 -->
    <el-dialog
      v-model="permissionDialogVisible"
      title="权限配置"
      width="800px"
      @close="handlePermissionDialogClose"
    >
      <div class="permission-config">
        <div class="permission-header">
          <h4>为角色 "{{ currentRole.name }}" 配置权限</h4>
          <div class="permission-actions">
            <el-button size="small" @click="handleExpandAll">展开全部</el-button>
            <el-button size="small" @click="handleCollapseAll">收起全部</el-button>
            <el-button size="small" @click="handleCheckAll">全选</el-button>
            <el-button size="small" @click="handleUncheckAll">取消全选</el-button>
          </div>
        </div>
        <el-tree
          ref="permissionTreeRef"
          :data="permissionTree"
          :props="treeProps"
          show-checkbox
          node-key="id"
          :default-checked-keys="checkedPermissions"
          @check="handlePermissionCheck"
        >
          <template #default="{ node, data }">
            <span class="permission-node">
              <el-icon v-if="data.type === 'menu'">
                <Menu />
              </el-icon>
              <el-icon v-else-if="data.type === 'button'">
                <Operation />
              </el-icon>
              <span>{{ node.label }}</span>
              <el-tag v-if="data.type" size="small" :type="data.type === 'menu' ? 'primary' : 'success'">
                {{ data.type === 'menu' ? '菜单' : '按钮' }}
              </el-tag>
            </span>
          </template>
        </el-tree>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="permissionDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSavePermission" :loading="permissionLoading">
            保存权限
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Delete, Download, Search, Refresh, Menu, Operation } from '@element-plus/icons-vue'

// 响应式数据
const loading = ref(false)
const submitLoading = ref(false)
const permissionLoading = ref(false)
const dialogVisible = ref(false)
const permissionDialogVisible = ref(false)
const selectedRoles = ref([])
const formRef = ref()
const permissionTreeRef = ref()
const currentRole = ref({})
const checkedPermissions = ref([])

// 搜索表单
const searchForm = reactive({
  name: '',
  code: '',
  status: ''
})

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 表单数据
const formData = reactive({
  id: null,
  name: '',
  code: '',
  description: '',
  status: 1,
  sort: 0,
  remark: ''
})

// 表单验证规则
const formRules = {
  name: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { min: 2, max: 50, message: '角色名称长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入角色编码', trigger: 'blur' },
    { pattern: /^[A-Z_]+$/, message: '角色编码只能包含大写字母和下划线', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入角色描述', trigger: 'blur' }
  ]
}

// 权限树配置
const treeProps = {
  children: 'children',
  label: 'name'
}

// 模拟数据
const tableData = ref([
  {
    id: 1,
    name: '超级管理员',
    code: 'SUPER_ADMIN',
    description: '系统超级管理员，拥有所有权限',
    userCount: 1,
    status: 1,
    sort: 1,
    createTime: '2024-01-01 09:00:00',
    remark: '系统内置角色'
  },
  {
    id: 2,
    name: '部门经理',
    code: 'DEPT_MANAGER',
    description: '部门经理，管理本部门业务',
    userCount: 5,
    status: 1,
    sort: 2,
    createTime: '2024-01-02 10:00:00',
    remark: '部门管理角色'
  },
  {
    id: 3,
    name: '普通员工',
    code: 'EMPLOYEE',
    description: '普通员工，基础业务操作权限',
    userCount: 20,
    status: 1,
    sort: 3,
    createTime: '2024-01-03 11:00:00',
    remark: '基础员工角色'
  },
  {
    id: 4,
    name: '财务人员',
    code: 'FINANCE_STAFF',
    description: '财务人员，财务相关权限',
    userCount: 3,
    status: 1,
    sort: 4,
    createTime: '2024-01-04 12:00:00',
    remark: '财务专用角色'
  },
  {
    id: 5,
    name: '仓库管理员',
    code: 'WAREHOUSE_ADMIN',
    description: '仓库管理员，仓储相关权限',
    userCount: 2,
    status: 0,
    sort: 5,
    createTime: '2024-01-05 13:00:00',
    remark: '仓库管理角色'
  }
])

// 权限树数据
const permissionTree = ref([
  {
    id: 1,
    name: '仪表盘',
    type: 'menu',
    children: [
      { id: 11, name: '查看仪表盘', type: 'button' }
    ]
  },
  {
    id: 2,
    name: '人力资源',
    type: 'menu',
    children: [
      {
        id: 21,
        name: '员工管理',
        type: 'menu',
        children: [
          { id: 211, name: '查看员工', type: 'button' },
          { id: 212, name: '新增员工', type: 'button' },
          { id: 213, name: '编辑员工', type: 'button' },
          { id: 214, name: '删除员工', type: 'button' }
        ]
      },
      {
        id: 22,
        name: '考勤管理',
        type: 'menu',
        children: [
          { id: 221, name: '查看考勤', type: 'button' },
          { id: 222, name: '考勤统计', type: 'button' }
        ]
      }
    ]
  },
  {
    id: 3,
    name: '采购管理',
    type: 'menu',
    children: [
      {
        id: 31,
        name: '供应商管理',
        type: 'menu',
        children: [
          { id: 311, name: '查看供应商', type: 'button' },
          { id: 312, name: '新增供应商', type: 'button' },
          { id: 313, name: '编辑供应商', type: 'button' },
          { id: 314, name: '删除供应商', type: 'button' }
        ]
      },
      {
        id: 32,
        name: '采购订单',
        type: 'menu',
        children: [
          { id: 321, name: '查看订单', type: 'button' },
          { id: 322, name: '创建订单', type: 'button' },
          { id: 323, name: '审核订单', type: 'button' },
          { id: 324, name: '取消订单', type: 'button' }
        ]
      }
    ]
  },
  {
    id: 4,
    name: '财务管理',
    type: 'menu',
    children: [
      {
        id: 41,
        name: '账户管理',
        type: 'menu',
        children: [
          { id: 411, name: '查看账户', type: 'button' },
          { id: 412, name: '新增账户', type: 'button' },
          { id: 413, name: '编辑账户', type: 'button' }
        ]
      },
      {
        id: 42,
        name: '财务报表',
        type: 'menu',
        children: [
          { id: 421, name: '查看报表', type: 'button' },
          { id: 422, name: '导出报表', type: 'button' }
        ]
      }
    ]
  },
  {
    id: 5,
    name: '系统管理',
    type: 'menu',
    children: [
      {
        id: 51,
        name: '用户管理',
        type: 'menu',
        children: [
          { id: 511, name: '查看用户', type: 'button' },
          { id: 512, name: '新增用户', type: 'button' },
          { id: 513, name: '编辑用户', type: 'button' },
          { id: 514, name: '删除用户', type: 'button' },
          { id: 515, name: '重置密码', type: 'button' }
        ]
      },
      {
        id: 52,
        name: '角色管理',
        type: 'menu',
        children: [
          { id: 521, name: '查看角色', type: 'button' },
          { id: 522, name: '新增角色', type: 'button' },
          { id: 523, name: '编辑角色', type: 'button' },
          { id: 524, name: '删除角色', type: 'button' },
          { id: 525, name: '权限配置', type: 'button' }
        ]
      }
    ]
  }
])

// 计算属性
const isEdit = computed(() => !!formData.id)
const dialogTitle = computed(() => isEdit.value ? '编辑角色' : '新增角色')

// 方法
const loadData = async () => {
  loading.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    pagination.total = tableData.value.length
  } catch (error) {
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.currentPage = 1
  loadData()
}

const handleReset = () => {
  Object.assign(searchForm, {
    name: '',
    code: '',
    status: ''
  })
  handleSearch()
}

const handleAdd = () => {
  resetForm()
  dialogVisible.value = true
}

const handleEdit = (row) => {
  Object.assign(formData, { ...row })
  dialogVisible.value = true
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除角色 "${row.name}" 吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 模拟删除操作
    const index = tableData.value.findIndex(item => item.id === row.id)
    if (index > -1) {
      tableData.value.splice(index, 1)
      ElMessage.success('删除成功')
      loadData()
    }
  } catch {
    // 用户取消删除
  }
}

const handleBatchDelete = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedRoles.value.length} 个角色吗？`,
      '批量删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 模拟批量删除操作
    const ids = selectedRoles.value.map(role => role.id)
    tableData.value = tableData.value.filter(item => !ids.includes(item.id))
    selectedRoles.value = []
    ElMessage.success('批量删除成功')
    loadData()
  } catch {
    // 用户取消删除
  }
}

const handleToggleStatus = async (row) => {
  const action = row.status === 1 ? '禁用' : '启用'
  try {
    await ElMessageBox.confirm(
      `确定要${action}角色 "${row.name}" 吗？`,
      `${action}确认`,
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 模拟状态切换操作
    row.status = row.status === 1 ? 0 : 1
    ElMessage.success(`${action}成功`)
  } catch {
    // 用户取消操作
  }
}

const handlePermission = (row) => {
  currentRole.value = row
  // 模拟加载角色权限
  checkedPermissions.value = [11, 211, 212, 311, 321, 411, 421, 511, 521]
  permissionDialogVisible.value = true
}

const handleExport = () => {
  ElMessage.success('导出功能开发中...')
}

const handleSelectionChange = (selection) => {
  selectedRoles.value = selection
}

const handleSizeChange = (size) => {
  pagination.pageSize = size
  loadData()
}

const handleCurrentChange = (page) => {
  pagination.currentPage = page
  loadData()
}

const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    submitLoading.value = true
    
    // 模拟提交操作
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    if (isEdit.value) {
      // 编辑角色
      const index = tableData.value.findIndex(item => item.id === formData.id)
      if (index > -1) {
        Object.assign(tableData.value[index], formData)
      }
      ElMessage.success('角色更新成功')
    } else {
      // 新增角色
      const newRole = {
        ...formData,
        id: Date.now(),
        userCount: 0,
        createTime: new Date().toLocaleString()
      }
      tableData.value.unshift(newRole)
      ElMessage.success('角色创建成功')
    }
    
    dialogVisible.value = false
    loadData()
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    submitLoading.value = false
  }
}

const handleDialogClose = () => {
  resetForm()
}

const resetForm = () => {
  Object.assign(formData, {
    id: null,
    name: '',
    code: '',
    description: '',
    status: 1,
    sort: 0,
    remark: ''
  })
  formRef.value?.clearValidate()
}

// 权限配置相关方法
const handleExpandAll = () => {
  // 展开所有节点
  const allKeys = []
  const collectKeys = (nodes) => {
    nodes.forEach(node => {
      allKeys.push(node.id)
      if (node.children) {
        collectKeys(node.children)
      }
    })
  }
  collectKeys(permissionTree.value)
  permissionTreeRef.value.setExpandedKeys(allKeys)
}

const handleCollapseAll = () => {
  // 收起所有节点
  permissionTreeRef.value.setExpandedKeys([])
}

const handleCheckAll = () => {
  // 全选所有权限
  const allKeys = []
  const collectKeys = (nodes) => {
    nodes.forEach(node => {
      allKeys.push(node.id)
      if (node.children) {
        collectKeys(node.children)
      }
    })
  }
  collectKeys(permissionTree.value)
  permissionTreeRef.value.setCheckedKeys(allKeys)
}

const handleUncheckAll = () => {
  // 取消全选
  permissionTreeRef.value.setCheckedKeys([])
}

const handlePermissionCheck = (data, checked) => {
  // 权限选择变化处理
  console.log('权限变化:', data, checked)
}

const handleSavePermission = async () => {
  try {
    permissionLoading.value = true
    
    // 获取选中的权限
    const checkedKeys = permissionTreeRef.value.getCheckedKeys()
    const halfCheckedKeys = permissionTreeRef.value.getHalfCheckedKeys()
    
    // 模拟保存权限操作
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    ElMessage.success('权限配置保存成功')
    permissionDialogVisible.value = false
  } catch (error) {
    ElMessage.error('保存权限失败')
  } finally {
    permissionLoading.value = false
  }
}

const handlePermissionDialogClose = () => {
  currentRole.value = {}
  checkedPermissions.value = []
}

// 生命周期
onMounted(() => {
  loadData()
})
</script>

<style scoped>
.role-management {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #e4e7ed;
}

.page-header h2 {
  margin: 0;
  color: #303133;
  font-size: 20px;
  font-weight: 600;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.search-section {
  background: #f8f9fa;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.table-section {
  background: white;
  border-radius: 8px;
  overflow: hidden;
}

.pagination {
  display: flex;
  justify-content: flex-end;
  padding: 20px;
  background: #fafafa;
  border-top: 1px solid #e4e7ed;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.permission-config {
  max-height: 500px;
  overflow-y: auto;
}

.permission-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #e4e7ed;
}

.permission-header h4 {
  margin: 0;
  color: #303133;
}

.permission-actions {
  display: flex;
  gap: 8px;
}

.permission-node {
  display: flex;
  align-items: center;
  gap: 8px;
  flex: 1;
}

.permission-node .el-icon {
  font-size: 16px;
}

.permission-node .el-tag {
  margin-left: auto;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }
  
  .header-actions {
    width: 100%;
    justify-content: flex-start;
    flex-wrap: wrap;
  }
  
  .search-section .el-form {
    flex-direction: column;
  }
  
  .search-section .el-form-item {
    margin-right: 0;
    margin-bottom: 15px;
  }
  
  .permission-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .permission-actions {
    width: 100%;
    justify-content: flex-start;
    flex-wrap: wrap;
  }
}
</style>